#include"muduo/net/EventLoopThread.h"
#include"muduo/net/TcpClient.h"
#include"muduo/base/CountDownLatch.h"

#include<iostream>
#include<functional>

class client{
    public:
        client(std::string ip,int port)
        :_client(_evlt.startLoop(),muduo::net::InetAddress(ip,port),"tmpclient")
        ,_latch(1)
        {
            std::cout<<"client init...\n";
            _client.setConnectionCallback(std::bind(&client::onConnection,this,std::placeholders::_1));
            _client.setMessageCallback(std::bind(&client::onMessage,this,
                std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
            
        }

        ~client(){}

        void connect(){
            _client.connect();
            _latch.wait();
        }

    bool send(const std::string& msg){
        
        if(_conn->connected()){
            _conn->send(msg);
        }else{
            return false;
        }
        return true;
    }
    private:
        void onConnection(const muduo::net::TcpConnectionPtr& conn){
            std::cout<<"onConnectin\n";
            if(conn->connected()){
                _conn = conn;
                _latch.countDown();
            }else{
                _conn.reset();
            }
        }
        void onMessage(const muduo::net::TcpConnectionPtr& conn,muduo::net::Buffer* buf,muduo::Timestamp time){
            std::cout<<buf->retrieveAllAsString()<<std::endl;            
        }
    private:
        muduo::CountDownLatch _latch;
        muduo::net::EventLoopThread _evlt; // 这俩成员顺序你整反了
        muduo::net::TcpClient _client;// client的初始化依赖于evlt，所以必须evlt在前
        muduo::net::TcpConnectionPtr _conn;
};

int main(){
    std::cout<<"Init..\n";
    client client("127.0.0.1",8081);
    std::cout<<"connect..\n";
    client.connect();
    std::cout<<"send...\n";
    while(1){   
        std::string input;
        std::cin>>input;
        client.send(input);
    }

    return 0;
}